package com.zfk.framework.variable_handling;

import org.apache.logging.log4j.LogManager;
import com.jayway.jsonpath.JsonPath;
import org.apache.logging.log4j.Logger;

import java.util.Map;

public class ResponseExtractor {
    private static final Logger logger = LogManager.getLogger(ResponseExtractor.class);
    public static void extractVariables(String responseBody, Map<String, Object> extract){
        if (extract.isEmpty()){
            logger.info("没有替换表达式，跳过提取");
            return;
        }
        //先遍历键值对，再进行jsonpath解析
        for (Map.Entry<String, Object> entry : extract.entrySet()){
            //变量名是 map的key，jsonPath是map的value，需要把janPath解析成具体的值 然后写入变量池中
            String variableName = entry.getKey();
            String jsonPath = entry.getValue().toString();
            try {
                Object extractedValue = JsonPath.read(responseBody, jsonPath);
                logger.info("开始提取变量 " + variableName + " = " + extractedValue+"到全局变量池");
                GlobalVariablePool.putIntoVariablePool(variableName, extractedValue);

            }catch (Exception e)
                {
                logger.error("变量提取错误 " + variableName, e);
            }
        }
    }
}
